package com.sz.common.base.utils;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;

/**
 * Function: TODO: ADD FUNCTION <br>
 * Author: Charles. <br>
 * Date: 2017-05-19 09:55:00.
 */
public class JsonUtils {

    /**
     * @param object
     * @return
     */
    public static String toJSONString(Object object) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(object);

            return json;
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }


    public static <T> T toObject(String jsonStr, Class<T> classType) {
        ObjectMapper mapper = new ObjectMapper();

        try {
            return mapper.readValue(jsonStr, classType);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }


    public static <T> List<T> toList(String str, Class<T> clazz) {

        ObjectMapper mapper = new ObjectMapper();
        //如果是Map类型
        T t = (T) mapper.getTypeFactory().constructParametricType(List.class, clazz);
        List<T> beanList = null;
        try {
            beanList = (List<T>) mapper.readValue(str, clazz);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return beanList;

    }


}
